#include "Mutex.hpp"
#include <string>
using namespace jc;

class ThreadDate
{
    public:
    ThreadDate(const std::string &n, Mutex &lock)
        :_name(n),
        _lockp(&lock)
        {
        }
        ~ThreadDate()
        {}
    std::string _name;
    Mutex* _lockp;
};

int ticket = 1000;

void *route(void *arg)
{
    ThreadDate* td = static_cast<ThreadDate*>(arg);
    while (1)
    {
        LockGuard l(*td->_lockp);
        if (ticket > 0) // 1. 判断
        {
            usleep(1000);                              
            ticket--;                                   
            printf("%s出票成功，剩余票数:%d\n", td->_name.c_str(), ticket); 
            
        }
        else
        {
            break;
        }
    }
    return nullptr;
}

int main()
{
    Mutex lock;
    pthread_t t1, t2, t3;
    ThreadDate* td1 = new ThreadDate("thread_1",lock);
    pthread_create(&t1,NULL,route,td1);

    ThreadDate* td2 = new ThreadDate("thread_2",lock);
    pthread_create(&t2,NULL,route,td2);

    ThreadDate* td3 = new ThreadDate("thread_3",lock);
    pthread_create(&t3,NULL,route,td3);

    //pthread_join(t1, NULL);
    //pthread_join(t2, NULL);
    //pthread_join(t3, NULL);
    sleep(1000000);

    return 0;
}